package com.orangelife.mobile.lookRepair.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;


import com.common.util.OrangePhoneUtil;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.PhoneCallUtil;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.adapter.MyImageViewGridAdapter;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.common.biz.Photo;
import com.thirdsdk.qiniu.QiniuService;
import com.thirdsdk.qiniu.QiniuService.QiniuListener;
import com.orangelife.mobile.constants.Constant;

import com.orangelife.mobile.photo.ImageActivity;
import com.orangelife.mobile.photo.MyGridView;
import com.orangelife.mobile.photo.PhotoActivity;

import com.orangelife.mobile.util.EmojiFilter;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;

public class ComplaintDeclarationActivity extends
		OrangeLifeBaseActivity {
	/** 标题中间的字 */
	private TextView tvTitle;
	/** 标题的电话图标 */
	private ImageView ivTitlePhone;
	/** 投诉申报问题 */
	private EditText etDeclarationContent;
	/** 照片的grideview */
	private MyGridView myGridView;
	/** gridview的adapter */
	private MyImageViewGridAdapter gvAdapter;
	/** 处理后的照片地址 */
	private String fileName = null;
	/** 照片路径 */
	private List<String> paths;
	/** 确认提交 */
	private Button btnSubmit;

	private Dialog dialog, dialogSubmit;
	/** 限制的最大字数 */
	int num = 50;
	String str = "";
	String strRepairID = "";
	String strPhone = "";
	String invcID = "";
	/** 登录还是忽略 */
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_complaint_declaration);
		initeView();
		findView();
	}

	/**
	 * 初始化
	 */
	private void initeView() {
		tvTitle = (TextView) findViewById(R.id.tv_title);
		myGridView = (MyGridView) findViewById(R.id.myGridview);
		btnSubmit = (Button) findViewById(R.id.btnSubmit);
		etDeclarationContent = (EditText) findViewById(R.id.etDeclarationContent);
		ivTitlePhone = (ImageView) findViewById(R.id.iv_title_right);
		ivTitlePhone.setVisibility(View.VISIBLE);
		ivTitlePhone.setBackgroundResource(R.drawable.icon_phone);

	}
	
	/**
	 * 赋值
	 */
	private void findView() {
		tvTitle.setText("投诉申报");
		setGridView();
		dialog = DialogHelper.getInstance().createLoadingDialog(
				ComplaintDeclarationActivity.this, Constant.LOADING);
		btnSubmit.setOnClickListener(listener);
		ivTitlePhone.setOnClickListener(listener);

		Intent data = getIntent();
		strRepairID = data.getStringExtra("repairID");
//		strPhone = data.getStringExtra("linkmanTel");
		invcID = data.getStringExtra("invcID");
		ivTitlePhone.setOnClickListener(listener);

		etDeclarationContent.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;
			private int selectionStart;
			private int selectionEnd;
			/** 匹配非表情符号的正则表达式 */
			/*
			 * private final String reg =
			 * "^([a-z]|[A-Z]|[0-9]|[\u2E80-\u9FFF]){3,}|@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?|[wap.]{4}|[www.]{4}|[blog.]{5}|[bbs.]{4}|[.com]{4}|[.cn]{3}|[.net]{4}|[.org]{4}|[http://]{7}|[ftp://]{6}$"
			 * ;
			 * 
			 * private Pattern pattern = Pattern.compile(reg);
			 */
			/** 输入表情前的光标位置 */
			private int cursorPos;
			/** 输入表情前EditText中的文本 */
			private String tmp;
			/** 是否重置了EditText的内容 */
			private boolean resetText;

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if ("".equals(str)) {
					if (!resetText) {
						/** 表情符号的字符长度最小为2 */
						if (count >= 2) {
							/** 提取输入的长度大于2的文本 */
							if (s.length() <= num) {
								CharSequence input = s.subSequence(start,
										start + count);
								/** 正则匹配是否是表情符号 */
								/*
								 * Matcher matcher = pattern.matcher(input
								 * .toString());
								 */
								if (!EmojiFilter.containsEmoji(input.toString())) {
									resetText = true;
									/** 是表情符号就将文本还原为输入表情符号之前的内容 */
									etDeclarationContent.setText(tmp);
									etDeclarationContent.invalidate();
									ToastHelper.getInstance()._toast("不支持表情输入");
									etDeclarationContent.setSelection(tmp
											.length());
								}
							} else {
								str = "over";
							}
						}
					} else {
						resetText = false;
					}
				}

				temp = s;
				Log.e("hhhhhhhh", s + "");
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				if (!resetText) {
					cursorPos = etDeclarationContent.getSelectionEnd();
					/**
					 * 这里用s.toString()而不直接用s是因为如果用s，那么，tmp和s在内存中指向的是同一个地址，s改变了，
					 * tmp也就改变了，那么表情过滤就失败了
					 */
					tmp = s.toString();
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
				selectionStart = etDeclarationContent.getSelectionStart();
				selectionEnd = etDeclarationContent.getSelectionEnd();
				if (temp.length() > num) {
					s.delete(selectionStart - 1, selectionEnd);
					ToastHelper.getInstance()._toast("投诉申报要在50字以内");
					etDeclarationContent.setText(s);
				}
			}
		});
	}

	/**
	 * 监听器
	 */
	private OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.iv_title_right:
				getPhone();
				break;
			case R.id.btnSubmit:
				if (StringUtil.isContainBlank(etDeclarationContent.getText()
						.toString())) {
					ToastHelper.getInstance()._toast("投诉申报的内容不能为空");
				} else {
					dialogSubmit = DialogHelper.getInstance()
							.createLoadingDialog(
									ComplaintDeclarationActivity.this,
									Constant.SUBMIT_LOADING);
					dialogSubmit.show();
					if(paths.size()>0){
						QiniuService qiniu = new QiniuService();
						qiniu.imgUpload(paths, new QiniuListener() {

							@Override
							public void request(String fileNames) {
								if (fileNames.equals("500")) {
									ToastHelper.getInstance()._toast(
											getResources().getString(
													R.string.photo_save_faild));
									return;
								}
								fileName = fileNames;
								sendComplaintDeclaration(fileName);
							}
						});
					}else{
						sendComplaintDeclaration(fileName);
					}
					

				}
				break;

			default:
				break;
			}

		}
	};

	/** 给照片gridview设置apdater和监听事件 */
	private void setGridView() {
		/** 设置adapter */
		paths = new ArrayList<String>();
		gvAdapter = new MyImageViewGridAdapter(
				ComplaintDeclarationActivity.this, paths, 5);
		myGridView.setAdapter(gvAdapter);
		gvAdapter.notifyDataSetChanged();
		/** 监听事件 */
		myGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				if (position == paths.size()) {
					Intent intent = new Intent(
							ComplaintDeclarationActivity.this,
							PhotoActivity.class);
					startActivityForResult(intent, 5);
				} else {

					Intent intent = new Intent(
							ComplaintDeclarationActivity.this,
							ImageActivity.class);
					intent.putExtra("position", position);
					intent.putExtra("path", paths.get(position));
					startActivityForResult(intent, 88);
				}
			}
		});

	}

	/**
	 * 提交投诉申报
	 */
	private void sendComplaintDeclaration(String fileName) {
		Map<String, Object> map = new HashMap<String, Object>();

		map.put("content", etDeclarationContent.getText().toString());
		map.put("invcRepaireID", strRepairID);
		if (fileName != null && !fileName.equals("")
				&& !fileName.equals("null")) {
			map.put("pics", fileName);
		}
		Map<String, Object> rootMap = new HashMap<String, Object>();
		rootMap.put("map", map);
		rootMap.put("url", Constant.URL_COMPLAINT_DECLARATION);
		rootMap.put("wat", 2);
		new JSONRequest(JSONRequest.POST, rootMap, handler,
				HttpUtil.ACTION_JSON);
	}
	/**
	 * 获取管理员电话
	 */
	private void getPhone() {
		OrangePhoneUtil.callCustomerService2(this);
	}

	/**
	 * 接收处理线程返回的消息
	 */
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Constant.WHAT_ERROR_HTTP:
				ToastHelper.getInstance()._toast(String.valueOf(msg.obj));
				break;
			case 1011:
				isLogin(dialog);
				break;
			case 1:
				String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
						.get("errInfo").toString();
				if (errInfo.equals("OK")) {
					DialogHelper.closeDialog(dialog);
					Map<String,Object> mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
							msg.obj.toString()).get("entity");
					String phone = mapDetail.get("linkmanTel").toString();
					PhoneCallUtil.getInstances().PhoneCall(ComplaintDeclarationActivity.this, phone);
				} else {
					DialogHelper.closeDialog(dialog);
					ToastHelper.getInstance()._toast(
							getResources().getString(
									R.string.complaintes_sumbite_fail));
				}
				break;
			case 2:
				errInfo = JSONHelper.jsonToMap(msg.obj.toString())
						.get("errInfo").toString();
				if (errInfo.equals("OK")) {
					DialogHelper.closeDialog(dialog);
					finish();
				} else {
					DialogHelper.closeDialog(dialog);
				}
				break;
			}
			if (dialog != null) {
				dialog.dismiss();
			}
		};
	};

	Photo photo = null;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == 5 && resultCode == 99) {
			if (data != null) {
				String photoPath = data.getStringExtra("photoPath");
				Context cxt = ComplaintDeclarationActivity.this;
				paths.add(photoPath);
				gvAdapter.resetImage(paths);
				gvAdapter.notifyDataSetChanged();
			} else {
				if (photo.photoUri != null) {
					String photoPath = photo.photoUri.getPath();
					paths.add(photoPath);
					gvAdapter.resetImage(paths);
					gvAdapter.notifyDataSetChanged();
				}

			}
		} else if (requestCode == 6 && resultCode == 99) {
			if (data != null) {
				String photoPath = Photo.getPath(data);
				Context cxt = ComplaintDeclarationActivity.this;
				paths.add(photoPath);
				gvAdapter.resetImage(paths);
				gvAdapter.notifyDataSetChanged();
			}

		} else if (requestCode == 88 && resultCode == 88) {
			if (data != null) {
				Bundle bundle = data.getExtras();
				int position = bundle.getInt("position");
				paths.remove(position);
				gvAdapter.resetImage(paths);
				gvAdapter.notifyDataSetChanged();
			}
		}
		gvAdapter.notifyDataSetChanged();
	}

}